from flask import Flask, render_template, request, redirect, url_for, send_file
from datetime import datetime
import database
import os

app = Flask(__name__)

# 首页路由
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # 获取表单数据
        process_emission = float(request.form['processEmission'])
        energy_consumption = float(request.form['energyConsumption'])
        resource_consumption = float(request.form['resourceConsumption'])
        process_factor = float(request.form['processFactor'])
        energy_factor = float(request.form['energyFactor'])
        resource_factor = float(request.form['resourceFactor'])

        # 计算总碳排放量
        total_carbon = (process_emission * process_factor) + \
                       (energy_consumption * energy_factor) + \
                       (resource_consumption * resource_factor)

        # 获取当前时间
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # 保存历史记录
        data = (timestamp, process_emission, energy_consumption, resource_consumption, process_factor, energy_factor, resource_factor, total_carbon)
        database.add_history_record(data)

        return redirect(url_for('index'))

    # 获取所有历史记录
    history_records = database.get_all_history_records()
    return render_template('index.html', history_records=history_records)

# 清除历史记录路由
@app.route('/clear_history', methods=['POST'])
def clear_history():
    database.clear_history_records()
    return redirect(url_for('index'))

# 保存历史记录为 CSV 文件路由
@app.route('/save_histroy', methods=['POST'])
def save_history():
    # csv_file = 'carbon_history.csv'
    csv_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),"carbon_history.csv")
    database.export_history_to_csv(csv_file)
    return send_file(csv_file, as_attachment=True)

if __name__ == '__main__':
    # 初始化数据库
    database.init_db()
    app.run(debug=True)